﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BusinessLogic.Model.Repository.NewsItemRepositories;
using BusinessLogic.Model.Repository.CommentsRepositories;
using System.Web;
using System.Configuration;
using System.Data.Linq;

namespace BusinessLogic.Model.Repository
{
    public class RepositoryFactory : IRepositoryFactory
    {
        private static readonly RepositoryFactory repositoryFactory = new RepositoryFactory();

        private RepositoryFactory()
        {
        }

        public static RepositoryFactory Instance
        {
            get { return repositoryFactory; }
        }

        public INewsItemRepository GetNewsItemRepository()
        {
            return new NewsItemRepository(GetDataContext());
        }

        public ICommentRepository GetCommentRepository()
        {
            return new CommentRepository(GetDataContext());
        }


        public virtual BlogNETDataContext GetDataContext()
        {
            //This method is not thread safe. It does not need to be because each web request is single threaded.
            var context = (BusinessLogic.Model.BlogNETDataContext)HttpContext.Current.Items["DataContext"];
            if (context == null)
            {
                context = new BlogNETDataContext(ConfigurationManager.ConnectionStrings["BlogNETDB"].ConnectionString);
                DataLoadOptions dlo = new DataLoadOptions();
                dlo.LoadWith<NewsItem>(ni => ni.Tags);
                context.LoadOptions = dlo;
                HttpContext.Current.Items["DataContext"] = context;
            }

            return context;
        }

    }
}
